#include "lib.h"
#include "rfile.h"
#include "rmanager.h"
#include "rresource.h"
using namespace Library;


//----------------------------------------------------------------------------
// Public
//
ResourceManager::ResourceManager()
	: m_cwd("")
{
	m_files		= new List<pResourceFile>;
	m_iterator	= m_files->listIterator();
}


ResourceManager::ResourceManager(const String & workingDirectory)
	: m_cwd(workingDirectory)
{
	m_files		= new List<pResourceFile>;
	m_iterator	= m_files->listIterator();
}


ResourceManager::~ResourceManager()
{
	delete m_iterator;
	m_iterator = 0;

	// Delete the resource files.
	m_files->vaporize();

	delete m_files;
	m_files = 0;
}


uint32
ResourceManager::open(const String & filename)
{
	String			pathFilename;
	pResourceFile	file;

	pathFilename  = m_cwd;
	pathFilename += filename;
	
	file = new ResourceFile();
	if (file && (!file->open(pathFilename) || !m_files->addIndex(0, file)))
	{
		delete file;
		file = 0;
	}

	return (uint32)file;
}


void
ResourceManager::close(uint32 id)
{
	pResourceFile file = (pResourceFile)id;

	if (m_files->remove(file))
		delete file;
}


void *
ResourceManager::get(const String & name)
{
	void * data;

	for (m_iterator->begin(); m_iterator->hasNext(); /* empty */)
	{
		data = m_iterator->next()->get(name);
		if (data)
			return data;
	}

	return 0;
}


bool8
ResourceManager::release(void * resource)
{
	return Resource::release(resource);
}
